import {
  createRouter,
  createWebHistory,
  RouteComponent,
  RouteLocationNormalized,
  RouteMeta,
  RouteRecordNormalized,
  RouteRecordRaw,
  _RouteRecordBase,
} from "vue-router";
import Layout from "@/layout/index.vue";
import routeLogin from "./modules/loginRoute";
import { REDIRECT_NAME } from "./constant";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/dashboard",
    component: Layout,
    redirect: "/dashboard/analysis",
    meta: {
      requiresAuth: true,
      title: "Dashboard",
      icon: "index",
    },
    name: "Dashboard",
    alias: ["/home", "/index", "/dashboard", "/"],
    children: [
      {
        path: "analysis",
        component: () => import("@/views/dashboard/analysis/index.vue"),
        name: "analysis",
        meta: {
          title: "分析页",
          icon: "analysis",
          affix: true,
          noCache: true,
          requiresAuth: true,
          hidden: false,
        },
      },
      {
        path: "workbench",
        name: "Workbench",
        component: () => import("@/views/dashboard/workbench/index.vue"),
        meta: {
          title: "工作台",
          icon: "workbench",
        },
      },
      {
        path: "test",
        name: "Test",
        component: () => import("@/views/dashboard/test/index.vue"),
        meta: {
          title: "测试",
          icon: "test",
        },
      },
    ],
  },
  {
    path: '/redirect',
    component: Layout,
    name: 'RedirectTo ',
    meta: {
      title: REDIRECT_NAME,
      hideBreadcrumb: true,
      hidden: true,
    },
    children: [
      {
        path: '/redirect/:path(.*)',
        name: REDIRECT_NAME,
        component: () => import('@/views/features/redirect.vue'),
        meta: {
          title: REDIRECT_NAME,
          hideBreadcrumb: true,
        },
      },
    ],
  },
  routeLogin,
];

const router = createRouter({
  // HTML5 模式
  history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

export function resetRouter() {
  const newRouter = router;
  router.resolve = newRouter.resolve; // reset router
}

interface Routers {
  icon: string;
  hidden?: boolean;
  name: string;
  path: string;
  // hidden: boolean
  redirect: string;
  component: string | _RouteRecordBase | RouteComponent;
  // alwaysShow: boolean
  meta: RouteMeta | any;
  children: Routers[];
  alias?: string[];
}

export function getRawRoute(
  route: RouteLocationNormalized | any
): RouteLocationNormalized {
  if (!route) return route;
  const { matched, ...opt } = route;
  return {
    ...opt,
    matched: (matched
      ? matched.map((item: RouteLocationNormalized) => ({
          meta: item.meta,
          name: item.name,
          path: item.path,
        }))
      : undefined) as RouteRecordNormalized[],
  };
}

export default router;
export { routes };
export type { Routers };
